<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon name="arrow-left" color="white" size="0.48rem" class="goback" @click="$router.back()"></van-icon>
      <!-- 搜索组件 -->
      <van-search v-fofo placeholder="请输入搜索关键字" background="#57c3c2" shape="round" @input="inputFn" v-model.trim="kw"></van-search>
    </div>

    <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="kw.length !== 0">
      <div class="sugg-item" v-for="(str, index) in suggestList" :key="index" v-html="lightFn(str, kw)" @click="suggestClickFn(str)"></div>
    </div>

    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用right-icon插槽来自定义右侧图标 -->
        <template #right-icon>
          <div>
            <van-icon name="delete" class="search-icon" @click="clearFn"></van-icon>
          </div>
        </template>
      </van-cell>
      <!-- 历史列表 -->
      <div class="history-list">
        <span class="history-item" v-for="(str, index) in history" :key="index" @click="historyClickFn(str)">{{ str }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { suggestListAPI } from '@/api'
import { setStorage, getStorage } from '@/utils/storage'
export default {
  name: 'Search',
  data() {
    return {
      kw: '', // 搜索关键字
      timer: null, // 防抖的定时器
      suggestList: [], // 联想建议列表文字数组
      history: JSON.parse(getStorage('his')) || [] // 搜索历史
    }
  },
  methods: {
    // 输入框-内容实时改变触发事件方法
    inputFn() {
      clearTimeout(this.timer)
      // 防抖：演示执行逻辑代码，事件再次触发时，清除上一个定时器
      if (this.kw.length === 0) {
        this.suggestList = []
      } else {
        this.timer = setTimeout(async () => {
          if (this.kw.length === 0) return
          const res = await suggestListAPI({
            keywords: this.kw
          })
          console.log(res)
          this.suggestList = res.data.data.options
        }, 300)
      }
    },
    // 专门处理字符串高亮关键字
    // OrginStr:原来字符串
    //target:关键字
    // 字符串.replace()=>替换掉第一个符合条件
    lightFn(originStr, target) {
      const reg = new RegExp(target, 'ig') // i忽略大小写，g全局都匹配
      return originStr.replace(reg, (match) => {
        return `<span style="color:red;">${match}</span>`
      })
    },
    // 输入框-搜索事件
    searchFn() {
      if (this.kw.length > 0) {
        this.history.push(this.kw)
        setTimeout(() => {
          this.$router.push({
            path: `/search_result/${this.kw}`
          })
        }, 0)
      }
    },
    // 联想菜单-点击事件
    suggestClickFn(str) {
      this.history.push(this.kw)
      setTimeout(() => {
        this.$router.push({
          path: `/search_result/${this.kw}`
        })
      }, 0)
    },
    // 搜索历史-点击事件
    historyClickFn(str) {
      setTimeout(() => {
        this.$router.push({
          path: `/search_result/${this.kw}`
        })
      }, 0)
    },
    // 清除历史记录
    clearFn() {
      this.history = []
    }
  },
  watch: {
    history: {
      deep: true,
      handler() {
        // Set:无序不重复的value集合体（无下角标）
        // 特点：你传入的数组类型。如果有重复元素，会自动清理重复元素，返回无重复的Set对象
        const theSet = new Set(this.history)
        // Set类型对象->转回->Array数组类型
        const arr = Array.from(theSet)
        setStorage('his', JSON.stringify(arr))
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-header {
  height: 80px;
  display: flex;
  align-items: center;
  background-color: #57c3c2;
  overflow: hidden;
}
.goback {
  padding-left: 14px;
}
// 搜索组件
.van-search {
  flex: 1;
}
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
// 搜索历史
.search-icon {
  font-size: 16px;
  line-height: inherit;
}
.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
